<template>
  <div>
    <h1 id="start">每月销售预测</h1>
    <div class="controls">
      <input v-model="searchQuery" type="text" placeholder="搜索销售产品或服务" @input="applyFilters" />
      开始日期：<input v-model="startDate" type="date" @change="applyFilters" />
      截止日期：<input v-model="endDate" type="date" @change="applyFilters" />
      <button class="repeat" @click="resetFilters">重置</button>
      <button class="add" @click="showAddPopup = true">新增</button>
      <button class="out" @click="exportExcel">导出excel文件</button>
    </div>
    <table class="tab" id="salesTable">
      <thead>
        <tr>
          <th>销售的产品或服务</th>
          <th>日期</th>
          <th>销售量(套)</th>
          <th>平均售价</th>
          <th>月销售额</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in paginatedData" :key="index">
          <td>{{ item.product }}</td>
          <td>{{ item.date }}</td>
          <td>{{ item.quantity }}</td>
          <td>{{ item.price }}</td>
          <td>{{ item.total }}</td>
          <td>
            <button class="bianji" @click="editItem(index)">编辑</button>
            <button class="shanchu" @click="deleteItem(index)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
    <!-- 新增弹窗 -->
    <div v-if="showAddPopup" class="popup">
      <div class="popup-content">
        <span class="close" @click="showAddPopup = false">&times;</span>
        <h2>新增产品或服务</h2>
        <label for="product">产品或服务：</label>
        <input v-model="newItem.product" type="text" id="product" placeholder="请输入:" />
        <label for="date">日期：</label>
        <input v-model="newItem.date" type="date" id="date" />
        <label for="quantity">销量：</label>
        <input v-model.number="newItem.quantity" type="number" id="quantity" placeholder="请输入:" @input="updateTotal('new')" />
        <label for="price">售价：</label>
        <input v-model.number="newItem.price" type="number" id="price" placeholder="请输入:" @input="updateTotal('new')" />
        <label for="total">总金额：</label>
        <input :value="newItem.total" type="text" id="total" readonly />
        <button @click="addItem">提交保存</button>
      </div>
    </div>
    <!-- 编辑弹窗 -->
    <div v-if="showEditPopup" id="editPopupForm" class="popup">
      <div class="popup-content">
        <span class="close" @click="showEditPopup = false">&times;</span>
        <h2>编辑产品或服务</h2>
        <label for="editProduct">产品或服务：</label>
        <input v-model="editItemData.product" type="text" id="editProduct" placeholder="请输入:" />
        <label for="editDate">日期：</label>
        <input v-model="editItemData.date" type="date" id="editDate" />
        <label for="editQuantity">销量：</label>
        <input v-model.number="editItemData.quantity" type="number" id="editQuantity" placeholder="请输入:" @input="updateTotal('edit')" />
        <label for="editPrice">售价：</label>
        <input v-model.number="editItemData.price" type="number" id="editPrice" placeholder="请输入:" @input="updateTotal('edit')" />
        <label for="editTotal">总金额：</label>
        <input :value="editItemData.total" type="text" id="editTotal" readonly />
        <button id="updateBtn" @click="updateItem">更新</button>
      </div>
    </div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';

export default {
  data() {
    return {
      salesData: [],
      showAddPopup: false,
      showEditPopup: false,
      newItem: {
        product: '',
        date: '',
        quantity: 0,
        price: 0,
        total: 0
      },
      editIndex: null,
      editItemData: {
        id: null,
        product: '',
        date: '',
        quantity: 0,
        price: 0,
        total: 0
      },
      searchQuery: '',
      startDate: '',
      endDate: '',
      currentPage: 1,
      itemsPerPage: 8,
      userId: null
    };
  },
  mounted() {
    // 检查是否已经刷新过
    if (!localStorage.getItem('refreshedOnce')) {
      localStorage.setItem('refreshedOnce', 'true');
      window.location.reload(); // 强制刷新页面
    }
  },
  created() {
    this.userId = localStorage.getItem('userId');
    if (this.userId) {
      this.fetchSalesData();
    } else {
      alert('请先登录');
      this.$router.push('/login');
    }
  },
  computed: {
    filteredData() {
      return this.salesData.filter(item => {
        const matchesSearch = item.product.includes(this.searchQuery);
        const matchesStartDate = !this.startDate || new Date(item.date) >= new Date(this.startDate);
        const matchesEndDate = !this.endDate || new Date(item.date) <= new Date(this.endDate);
        return matchesSearch && matchesStartDate && matchesEndDate;
      });
    },
    totalPages() {
      return Math.ceil(this.filteredData.length / this.itemsPerPage);
    },
    paginatedData() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.filteredData.slice(start, end);
    }
  },
  methods: {
    fetchSalesData() {
      fetch(`http://82.156.19.25:5000/get_sales_data?user_id=${this.userId}`)
        .then(response => response.json())
        .then(data => {
          if (data.success) {
            this.salesData = data.sales.sort((a, b) => b.id - a.id);
          } else {
            alert(data.message);
          }
        })
        .catch(error => {
          console.error('Error fetching sales data:', error);
        });
    },
    applyFilters() {
      this.currentPage = 1;
      this.updatePaginatedData();
    },
    resetFilters() {
      this.searchQuery = '';
      this.startDate = '';
      this.endDate = '';
      this.applyFilters();
    },
    updateTotal(type) {
      if (type === 'new') {
        this.newItem.total = this.newItem.quantity * this.newItem.price;
      } else if (type === 'edit') {
        this.editItemData.total = this.editItemData.quantity * this.editItemData.price;
      }
    },
    addItem() {
      if (this.newItem.product && this.newItem.date && this.newItem.quantity && this.newItem.price) {
        const formattedDate = `${this.newItem.date}`;
        fetch('http://82.156.19.25:5000/add_sales_data', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            user_id: this.userId,
            product: this.newItem.product,
            date: formattedDate,
            quantity: this.newItem.quantity,
            price: this.newItem.price,
            total: this.newItem.total
          })
        })
          .then(response => response.json())
          .then(data => {
            if (data.success) {
              this.fetchSalesData(); // 更新数据而非刷新页面
              this.showAddPopup = false;
            } else {
              alert(data.message);
            }
          })
          .catch(error => {
            console.error('错误的添加信息', error);
          });
      } else {
        alert('请完整填写所有字段。');
      }
    },
    editItem(index) {
      const item = this.paginatedData[index];
      this.editIndex = index;
      this.editItemData = { ...item };
      this.showEditPopup = true;
    },
    updateItem() {
      if (this.editItemData.product && this.editItemData.date && this.editItemData.quantity && this.editItemData.price) {
        const formattedDate = `${this.editItemData.date}`;
        fetch('http://82.156.19.25:5000/update_sales_data', {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            user_id: this.userId,
            id: this.editItemData.id,
            product: this.editItemData.product,
            date: formattedDate,
            quantity: this.editItemData.quantity,
            price: this.editItemData.price,
            total: this.editItemData.total
          })
        })
          .then(response => response.json())
          .then(data => {
            if (data.success) {
              const index = this.salesData.findIndex(item => item.id === this.editItemData.id);
              if (index !== -1) {
                this.salesData.splice(index, 1, { ...this.editItemData, date: formattedDate });
                this.salesData.sort((a, b) => b.id - a.id); // 按 id 逆序排序
              }
              this.showEditPopup = false;
              this.applyFilters();
            } else {
              alert(data.message);
            }
          })
          .catch(error => {
            console.error('错误的更新请求:', error);
          });
      } else {
        alert('请完整填写所有字段。');
      }
    },
    deleteItem(index) {
      const itemId = this.paginatedData[index].id;
      if (confirm('确定要删除这条记录吗？')) {
        fetch('http://82.156.19.25:5000/delete_sales_data', {
          method: 'DELETE',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            user_id: this.userId,
            id: itemId
          })
        })
          .then(response => response.json())
          .then(data => {
            if (data.success) {
              this.salesData = this.salesData.filter(item => item.id !== itemId);
              this.applyFilters();
            } else {
              alert(data.message);
            }
          })
          .catch(error => {
            console.error('错误的删除信息:', error);
          });
      }
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    },
    exportExcel() {
      // 计算总计
      const totalQuantity = this.filteredData.reduce((sum, item) => sum + item.quantity, 0);
      const totalRevenue = this.filteredData.reduce((sum, item) => sum + parseFloat(item.total), 0);

      // 创建导出的表格数据
      const tableData = this.filteredData.map(item => [
        item.product,
        item.date,
        item.quantity,
        item.price,
        item.total
      ]);

      // 添加表头
      tableData.unshift([
        '销售的产品或服务',
        '日期',
        '销售量(套)',
        '平均售价',
        '月销售额'
      ]);

      // 添加总计行
      tableData.push([
        '总计', // 第一列
        '', // 第二列留空
        totalQuantity, // 销售量总计
        '', // 第四列留空
        totalRevenue.toFixed(2) // 月销售额总计，保留两位小数
      ]);

      // 创建 Excel 工作表
      const worksheet = XLSX.utils.aoa_to_sheet(tableData);

      // 自动调整列宽
      const colWidths = tableData[0].map((_, i) => ({
        wch: Math.max(...tableData.map(row => (row[i] ? row[i].toString().length : 10))) + 4 // 增加一点空间
      }));
      worksheet['!cols'] = colWidths;

      // 创建工作簿
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, '销售数据');

      // 导出 Excel 文件
      XLSX.writeFile(workbook, '销售成本和计划.xlsx');
    }
  }
}
</script>

<style scoped>
body {
  font-family: Arial, sans-serif;
  background-color: #062745;
  align-items: center;
  flex-direction: column;
  min-height: 100vh;
  margin: 0;
}

.controls {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.controls input[type='text']{
  margin-left: 125px;
  margin-right: 10px;
  padding: 5px;
  border-radius: 4px;
  border: 1px solid #ddd;
}
.controls input[type='month'],
.controls input[type='date'] {
  margin-left: 1px;
  margin-right: 10px;
  padding: 5px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

table {
  border-collapse: collapse;
  width: 100%;
}

table {
  border-collapse: collapse;
  width: 80%;
  margin: 20px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

th,
td {
  border: 1px solid #ddd;
  padding: 12px 15px;
  text-align: center;
}

th {
  background-color: #4caf50;
  color: white;
}

tr:nth-child(even) {
  background-color: #f2f2f2;
}

tr:hover {
  background-color: #f1f1f1;
}

h1 {
  margin-left: 15px;
}
.repeat{
  background-color: rgb(134, 173, 16);
  margin-bottom: 5px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s; /* 添加过渡效果 */
}
.add {
  background-color: rgb(27, 128, 7);
  margin-bottom: 5px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s; /* 添加过渡效果 */
}
.out:hover,
.add:hover,
.bianji:hover,
.shanchu:hover {
  background-color: rgb(103, 17, 240);
}

.out {
  background-color: #f07c3e;
  margin-bottom: 5px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s;
}

.popup {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.popup-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  width: 300px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  position: relative;
}

.close {
  position: absolute;
  right: 20px;
  top: 20px;
  cursor: pointer;
  font-size: 18px;
  color: #333;
}

.bianji {
  background-color: rgb(201, 43, 31);
  margin-bottom: 10px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s; /* 添加过渡效果 */
}
.tab {
  margin-left: 125px;
}
.shanchu {
  background-color: rgb(9, 4, 48);
  margin-bottom: 10px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s; /* 添加过渡效果 */
}

button {
  cursor: pointer;
}
.popup-content input[type='month'],
.popup-content input[type='text'],
.popup-content input[type='number'],
.popup-content input[type='date'] {
  width: 100%;
  padding: 8px;
  margin-bottom: 15px;
  border-radius: 4px;
  border: 1px solid #ddd;
  font-size: 14px;
}

input[type='text']:focus,
input[type='number']:focus,
input[type='month']:focus,
input[type='date']:focus {
  border-color: #4caf50;
}


button {
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 12px 24px;
  cursor: pointer;
  margin-top: 10px;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}


.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.pagination button {
  margin: 0 5px;
  padding: 8px 16px;
  border-radius: 4px;
  background-color: #f2f2f2;
  color: #333;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s;
}

.pagination button:hover {
  background-color: #ddd;
}

</style>
